package dump

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/v2/util/gconv"
	"reflect"
	"strings"
)

func GetCompositeString(composite any) string {
	// 创建一个 buffer 用于存储编码后的内容
	var buf bytes.Buffer
	encoder := json.NewEncoder(&buf)
	encoder.SetEscapeHTML(false)

	// 将 composite 中的内容编码为 JSON 格式并写入 buffer
	err := encoder.Encode(composite)
	if err != nil {
		return gconv.String(composite)
	}
	return buf.String()
}

func GetCompositeStringV2(composite any) string {
	if res, ok := composite.([]interface{}); ok {
		for _, v := range res {
			switch v.(type) {

			}
		}
	}

	// 尝试 JSON 编码
	var buf bytes.Buffer
	encoder := json.NewEncoder(&buf)
	encoder.SetEscapeHTML(false)

	if err := encoder.Encode(composite); err == nil {
		return strings.TrimSpace(buf.String())
	}

	// 如果 JSON 编码失败，尝试递归处理结构体
	val := reflect.ValueOf(composite)
	if val.Kind() == reflect.Ptr {
		val = val.Elem()
	}

	if val.Kind() == reflect.Struct {
		var result strings.Builder
		result.WriteString("{")
		first := true

		for i := 0; i < val.NumField(); i++ {
			if !first {
				result.WriteString(", ")
			}
			first = false

			field := val.Type().Field(i)
			fieldValue := val.Field(i)

			result.WriteString(field.Name)
			result.WriteString(": ")
			result.WriteString(GetCompositeString(fieldValue.Interface()))
		}

		result.WriteString("}")
		return result.String()
	}

	// 最后回退到简单格式化
	return fmt.Sprintf("%+v", composite)
}
